﻿using System;
using System.Web.Mvc;
using NHibernate;

namespace SessionByActionFilter {

  [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
  public class NeedsPersistenceAttribute: NHibernateSessionAttribute {

    protected ISession session {
      get {
        return sessionFactory.GetCurrentSession();
      }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
      base.OnActionExecuting(filterContext);
      session.BeginTransaction();
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext) {
      var tx = session.Transaction;
      if (tx != null && tx.IsActive) {
        session.Transaction.Commit();
      }
      base.OnActionExecuted(filterContext);
    }
  }


}